# -*- coding: utf-8 -*-
# @Time    : 2018/2/4 16:19
# @Author  : Soft
# @File    : service.py
from module.TimeUtils import *
from module.models import Admin, db, Page
import logging

log = logging.getLogger('Admin Service LOG')

class AdminService:

    def __init__(self):
        pass

    @db.atomic()
    def login(self, name='', pass_wd='', flag=False):
        result = Admin.select().where(Admin.ad_name == name, Admin.ad_pass == pass_wd)
        if len(result) >= 1:
            end_time = get_time()
            if flag:
                Admin.update(end_time=end_time).where(Admin.ad_name == name,
                                                     Admin.ad_pass == pass_wd).execute()
            return True, result[0]
        return False, None

    @db.atomic()
    def add(self, **admin):
        end_time = get_time()
        return Admin.insert(end_time=end_time, **admin).execute()

    @db.atomic()
    def remove(self, aid=None):
        return Admin.delete_by_id(aid)

    @db.atomic()
    def change(self, old_name=None, **admin):
        return Admin.update(**admin).where(Admin.ad_name == old_name).execute()

    def get_by_id(self, aid=0):
        return Admin.find_by_id(pk=aid)

    def query_name(self, name=None):
        """
        通过ad_name搜索用户
        :param name: 用户名
        """
        result = Admin.select().where(Admin.ad_name == name)
        if len(result):
            return result[0].to_dict()
        return None

    def pages(self, page=1, size=12):
        data = []
        results = Admin.select().order_by(Admin.id.desc()).paginate(page, size)
        for result in results:
            data.append(result.to_dict())
        Page.result = data
        Page.page = page
        Page.limit = size
        Page.total = Admin.select().count()
        return Page.to_dict()

    def query_sql(self, sql, *param):
        l = []
        for r in Admin.raw(sql, *param):
            l.append(r.to_dict())
        return l

    @staticmethod
    def get_name_pass(aid):  # 提供给验证登录用 返回账号和密码
        try:
            admin = Admin.get_by_id(int(aid))
            return admin.ad_name, admin.ad_pass
        except BaseException as e:
            log.warn('获取用户失败--> %s' % e)
            return ' ', ' '
